package com.lanou3g.ptp.sign.job;

import com.alibaba.dubbo.config.annotation.Reference;
import com.lanou3g.ptp.base.service.BaseService;
import com.lanou3g.ptp.entity.Base;
import com.lanou3g.ptp.entity.Message;
import com.lanou3g.ptp.entity.Student;
import com.lanou3g.ptp.entity.Task;
import com.lanou3g.ptp.message.service.MessageService;
import com.lanou3g.ptp.signInDate.service.SignInDateService;
import com.lanou3g.ptp.task.service.TaskService;
import com.lanou3g.ptp.taskstudent.service.TaskStudentService;
import com.lanou3g.ptp.vo.TemplateData;
import com.lanou3g.ptp.vo.WxTmplMsg;
import com.lanou3g.ptp.wx.service.WxService;
import org.quartz.JobExecutionContext;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class SignJob extends QuartzJobBean {

    @Reference
    private TaskService taskService;
    @Reference
    private TaskStudentService taskStudentService;
    @Reference
    private WxService wxService;
    @Reference
    private BaseService baseService;
    @Reference
    private SignInDateService signInDateService;
    @Reference
    private MessageService messageService;

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) {
        List<Task> tasks = taskService.findByStatus(Task.STATUS_RUNNING);
        for (Task task : tasks) {
            Long taskId = task.getId();
            boolean ifTodayInSignInDates = signInDateService.ifTodayInSignInDates(taskId);
            if (ifTodayInSignInDates) {
                Base base = baseService.findById(task.getBaseId());
                List<Student> students = taskStudentService.findStudentsByTaskId(taskId);
                for (Student student : students) {
                    String openId = student.getOpenId();
                    if (openId != null && !openId.trim().equals("")) {
                        Map<String, TemplateData> data = new HashMap<>();
                        data.put("keyword1", new TemplateData("地址围栏"));
                        data.put("keyword2", new TemplateData(task.getName()));
                        data.put("keyword3", new TemplateData(base.getAddress()));
                        String content = "今天不要忘记打卡呀！（已打卡请忽略） ";
                        data.put("keyword4", new TemplateData(content));
                        boolean result = wxService.sendMessage(openId, WxTmplMsg.TYPE_SIGN, data);
                        if (result) {
                            Message message = new Message();
                            message.setStudentId(student.getId());
                            message.setTaskId(taskId);
                            message.setContent(content);
                            messageService.saveSignMessage(message);
                        }
                    }
                }
            }
        }
    }
}
